/*
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.fabric8.kubernetes.model.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GoIntegerDeserializer extends StdDeserializer<Integer> implements ContextualDeserializer {

  private static final Pattern OCTAL = Pattern.compile("(0[oO]?)([0-7]+)");
  private static final GoIntegerDeserializer APPLICABLE_INSTANCE = new GoIntegerDeserializer(true);
  private static final Set<String> APPLICABLE_FIELDS = new HashSet<>(Arrays.asList("mode", "defaultMode"));

  private final boolean applicable;

  protected GoIntegerDeserializer() {
    this(false);
  }

  private GoIntegerDeserializer(boolean applicable) {
    super(Integer.class);
    this.applicable = applicable;
  }

  @Override
  public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    final String value = p.getText();
    if (value == null) {
      return null;
    }
    if (applicable) {
      final Matcher matcher = OCTAL.matcher(value);
      if (matcher.find()) {
        return Integer.valueOf(matcher.group(2), 8);
      }
    }
    return _parseInteger(ctxt, value);
  }

  @Override
  public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
    if (property != null && APPLICABLE_FIELDS.contains(property.getName())) {
      return APPLICABLE_INSTANCE;
    }
    return this;
  }
}
